package com.ykj.filter;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;



public class IpServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		try {
			String  ip = getIpAddr(request);
			 System.out.println("公网Ip===>"+ip);
			 request.getSession().setAttribute("ip", ip);
			 
			 String addressByIP = getAddressByIP(ip);
			 System.out.println("所在地区===>"+addressByIP);
			 request.getSession().setAttribute("addressByIP", addressByIP);
			 
			 request.getRequestDispatcher("index.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取访问用户的客户端IP（适用于公网与局域网）.
	 */
	public static final String getIpAddr(final HttpServletRequest request)
	        throws Exception {
	    if (request == null) {
	        throw (new Exception("getIpAddr method HttpServletRequest Object is null"));
	    }
	    String ipString = request.getHeader("x-forwarded-for");
	    if (isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
	        ipString = request.getHeader("Proxy-Client-IP");
	    }
	    if (isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
	        ipString = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if (isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
	        ipString = request.getRemoteAddr();
	    }
	 
	    // 多个路由时，取第一个非unknown的ip
	    final String[] arr = ipString.split(",");
	    for (final String str : arr) {
	        if (!"unknown".equalsIgnoreCase(str)) {
	            ipString = str;
	            break;
	        }
	    }
	 
	    return ipString;
	}
	
	
	public  static boolean isBlank(String str){
		if (str!=null && !"".equals(str)) {
			return false;	
		}
		return true;
	}
	
	public static String getAddressByIP(String strIP) {  
        try {  
            /*URL url = new URL("https://ipinfo.io");  */
//            URL url = new URL("http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip=218.17.162.69");  
            URL url = new URL("http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip="+strIP);  
            URLConnection conn = url.openConnection();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));  
            String line = null;  
            StringBuffer result = new StringBuffer();  
            while ((line = reader.readLine()) != null) {  
                result.append(line);  
            }  
            reader.close();  
            String ipAddr = result.toString();  
            try {  
                JSONObject obj1= new JSONObject(ipAddr);  
                if("0".equals(obj1.get("status").toString())){  
                JSONObject obj2= new JSONObject(obj1.get("content").toString());  
                JSONObject obj3= new JSONObject(obj2.get("address_detail").toString());  
//                return obj3.get("city").toString();  
                return obj1.get("address").toString(); 
                }else{  
                    return "读取失败";  
                }  
            	/*JSONObject obj1= new JSONObject(ipAddr);  
            	String country=obj1.getString("country");
            	String ip=obj1.getString("ip");
            	return country;*/
            } catch (JSONException e) {  
                e.printStackTrace();  
                return "读取失败";  
            }  
              
        } catch (IOException e) {  
            return "读取失败";  
        }  
    }  
	
   
}
